<template>
  <n-drawer v-model:show="showDrawer" placement="right" width="420">
    <n-drawer-content>
      <template #header>
        <div style="display: flex; justify-content: space-between; align-items: center; width: 100%;">
          <span>历史会话</span>
          <n-popconfirm
            positive-text="确认"
            negative-text="取消"
            @positive-click="deleteAllSessions"
          >
            <template #trigger>
              <n-button text type="error" size="small">
                <n-icon size="16">
                  <TrashBinOutline />
                </n-icon>
              </n-button>
            </template>
            确定要清空所有历史会话吗？此操作不可恢复。
          </n-popconfirm>
        </div>
      </template>
      <div class="drawer-history-list">
        <template v-for="(group, date) in groupedSessions" :key="date">
          <div class="drawer-history-date">{{ date }}</div>
          <ul>
            <li 
              v-for="session in group" 
              :key="session.sessionId" 
              :class="{active: session.sessionId === currentSessionId}"
              @click="selectSession(session.sessionId)"
              @mouseenter="hoverSessionId = session.sessionId"
              @mouseleave="hoverSessionId = ''">
              <span class="drawer-history-title" :title="session.title || session.sessionId">
                {{ session.title || session.sessionId }}
              </span>
              <span 
                v-if="hoverSessionId === session.sessionId && session.sessionId !== currentSessionId" 
                class="drawer-history-delete" 
                @click.stop="deleteSession(session)">
                <n-icon size="16">
                  <TrashOutline />
                </n-icon>
              </span>
              <span v-else class="drawer-history-time">{{ formatTime(session.createTime) }}</span>
            </li>
          </ul>
        </template>
      </div>
    </n-drawer-content>
  </n-drawer>
</template>

<script setup lang="ts">
import { NDrawer, NDrawerContent, NIcon, NButton, NPopconfirm } from 'naive-ui'
import { TrashOutline, TrashBinOutline } from '@vicons/ionicons5'
import { ref, computed, watch } from 'vue'
import { useRouter } from 'vue-router'
import { aiService } from '../../shared/services'
import { useUserStore } from '../../auth/stores/user'

const router = useRouter()
const userStore = useUserStore()

// Props
const props = defineProps({
  show: { type: Boolean, default: false },
  currentSessionId: { type: String, default: '' },
  userId: { type: [Number, String], required: true }  // 修改为接受Number或String类型
})

// Emits
const emit = defineEmits(['update:show', 'session-selected'])

// State
const sessions = ref<any[]>([])
const hoverSessionId = ref('')

// Computed
const showDrawer = computed({
  get: () => props.show,
  set: (val: boolean) => emit('update:show', val)
})

const groupedSessions = computed(() => {
  const groups: Record<string, any[]> = {}
  for (const s of sessions.value) {
    const date = s.updateTime ? formatDate(s.updateTime) : (s.createTime ? formatDate(s.createTime) : null)
    if (!date) continue
    if (!groups[date]) groups[date] = []
    groups[date].push(s)
  }
  return Object.fromEntries(Object.entries(groups).sort((a, b) => b[0].localeCompare(a[0])))
})

// Methods
function formatDate(dateStr: string) {
  const d = new Date(dateStr)
  const y = d.getFullYear()
  const m = (d.getMonth() + 1).toString().padStart(2, '0')
  const day = d.getDate().toString().padStart(2, '0')
  return `${y}/${m}/${day}`
}

function formatTime(dateStr: string) {
  const d = new Date(dateStr)
  return d.toTimeString().slice(0, 5)
}

async function fetchSessions() {
  try {
    const res = await aiService.getSessionHistoryList()
    sessions.value = res.data || []
    console.log('获取到的会话历史:', sessions.value);
  } catch (error) {
    console.error('获取历史会话失败:', error);
  }
}

async function selectSession(sessionId: string) {
  // 更新Pinia中的当前会话ID
  userStore.setCurrentSessionId(sessionId)
  
  // 通知父组件会话已选择
  emit('session-selected', sessionId)
  
  // 关闭抽屉
  showDrawer.value = false
  
  // 导航到新的会话
  setTimeout(() => {
    router.push(`/chat/${sessionId}`)
  }, 0)
  
  // 触发会话切换事件，确保ChatWindow能够更新对话气泡
  window.dispatchEvent(new CustomEvent('sessionChange', {
    detail: sessionId
  }) as any)
}

async function deleteSession(session: any) {
  try {
    await aiService.deleteSessionHistory(session.sessionId)
    await fetchSessions()
    
    // 如果删除的是当前会话，需要重定向到新会话
    if (session.sessionId === props.currentSessionId) {
      // 创建新会话或重定向到首页
      router.push('/')
    }
    // 注意：删除会话后不关闭抽屉，保持抽屉打开状态
  } catch (error) {
    console.error('删除会话失败:', error);
  }
}

async function deleteAllSessions() {
  try {
    await aiService.deleteAllSessionHistories()
    await fetchSessions()
    
    // 如果当前有会话，需要重定向到首页
    if (props.currentSessionId) {
      router.push('/')
    }
    // 注意：删除所有会话后不关闭抽屉，保持抽屉打开状态
  } catch (error) {
    console.error('清空所有会话失败:', error);
  }
}

// 暴露给父组件的方法
async function open() {
  await fetchSessions()
  showDrawer.value = true
}

// 监听show变化，自动加载数据
watch(() => props.show, (newShow) => {
  if (newShow) {
    fetchSessions()
  }
})

// 对外暴露方法
defineExpose({
  open
})
</script>

<style scoped>
.drawer-history-list {
  padding: 0;
}

.drawer-history-date {
  font-weight: bold;
  color: #666;
  margin: 16px 0 8px 0;
  font-size: 14px;
}

.drawer-history-list ul {
  list-style: none;
  padding: 0;
  margin: 0;
}

.drawer-history-list li {
  padding: 12px 16px;
  border-radius: 6px;
  margin-bottom: 4px;
  cursor: pointer;
  display: flex;
  justify-content: space-between;
  align-items: center;
  transition: all 0.2s ease;
}

.drawer-history-list li:hover {
  background-color: #f5f5f5;
}

.drawer-history-list li.active {
  background-color: #e6f7ff;
  border-left: 3px solid #1890ff;
}

.drawer-history-title {
  flex: 1;
  font-size: 14px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  margin-right: 8px;
}

.drawer-history-time {
  font-size: 12px;
  color: #999;
  white-space: nowrap;
}

.drawer-history-delete {
  color: #ff4d4f;
  cursor: pointer;
  padding: 4px;
  border-radius: 4px;
  transition: background-color 0.2s;
}

.drawer-history-delete:hover {
  background-color: #fff1f0;
}
</style>